import cv2

if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread("C:\\Users\\20436\Desktop\meiguoguoqi.jpg")

    # 2. 灰度化
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)

    # 3. 二值化
    _, image_np_thresh = cv2.threshold(
        image_np_gray,
        75,
        255,
        cv2.THRESH_BINARY
    )

    # 4. 查找轮廓
    contours, hierarchy = cv2.findContours(
        image_np_thresh,
        cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE
    )


    print(len(contours))
    # 5. 外界轮廓
    contour_image = image_np.copy()
    # 遍历除了最后一个轮廓的其他轮廓
    for cnt in contours[:len(contours)-1]:
        # 计算最小外接圆
        # 返回值：圆心和半径
        (x, y), radius = cv2.minEnclosingCircle(cnt)
        # 转整形
        x, y, radius = int(x), int(y), int(radius)
        print(f"圆心({x},{y}), 半径{radius}")
        # 画圆
        cv2.circle(
            contour_image,  # 在哪里画
            (x, y),  # 圆心
            radius,  # 半径
            (255, 255, 0),  # 颜色
            2,  # 粗度
            cv2.LINE_AA  # 抗锯齿
        )

    # 6. 图片输出
    cv2.imshow('image_np_thresh', image_np_thresh)
    cv2.imshow('image_np_gray', image_np_gray)
    cv2.imshow('contour_image', contour_image)
    cv2.imwrite('contour_image.jpg',contour_image)
    cv2.waitKey(0)
